﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace ThinkPHP5AutoCode
{
    public partial class WinFormsApp : Form
    {
        public string author = "作者:快乐的làngYā(hulangfy@163.com)";
        public string generate = "创建时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        public WinFormsApp()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;//窗口居中
            // windows 分辨率大小
            int winWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
            int winHeight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
            // 设置WinForms窗口大小
            Size size = new Size(1366, 768);
            this.Size = size;
        }
        private void WinFormsApp_Load(object sender, EventArgs e)
        {
            //获取当前系统桌面路径
            string dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            this.txtOutPut.Text = dir + "\\ThinkPHP5AutoCode";
            //
            this.txtShow.Text = "预览区域";
            // 获取之前保存的配置
            string hostname = ConfigHelper.GetAppConfig("hostname");
            string hostport = ConfigHelper.GetAppConfig("hostport");
            string database = ConfigHelper.GetAppConfig("database");
            string username = ConfigHelper.GetAppConfig("username");
            string password = ConfigHelper.GetAppConfig("password");
            string prefix = ConfigHelper.GetAppConfig("prefix");
            string ModularName = ConfigHelper.GetAppConfig("ModularName");
            string Common = ConfigHelper.GetAppConfig("Common");
            string OutPut = ConfigHelper.GetAppConfig("OutPut");
            this.txtHostName.Text = string.IsNullOrWhiteSpace(hostname) ? "localhost" : hostname;
            this.txtHostPort.Text = string.IsNullOrWhiteSpace(hostport) ? "3306" : hostport;
            this.txtDataBase.Text = string.IsNullOrWhiteSpace(database) ? "zjjcms" : database;
            this.txtUserName.Text = string.IsNullOrWhiteSpace(username) ? "root" : username;
            this.txtUserPwd.Text = string.IsNullOrWhiteSpace(password) ? "123456" : password;
            this.txtPrefix.Text = string.IsNullOrWhiteSpace(prefix) ? "zjjcms_" : prefix;
            this.txtModularName.Text = string.IsNullOrWhiteSpace(ModularName) ? "admin" : ModularName;
            this.txtCommon.Text = string.IsNullOrWhiteSpace(Common) ? "common" : Common;
            if (!string.IsNullOrWhiteSpace(OutPut)) {
                this.txtOutPut.Text = OutPut;
            }
        }
        public MySqlConnection conn;
        List<string> listleft = new List<string>();
        List<string> listright = new List<string>();

        private void setReadOnlyTrue()
        {
            this.txtHostName.ReadOnly = true;
            this.txtHostPort.ReadOnly = true;
            this.txtDataBase.ReadOnly = true;
            this.txtUserName.ReadOnly = true;
            this.txtUserPwd.ReadOnly = true;
            this.btnLinkConn.Enabled = false;
        }
        private void setReadOnlyFalse()
        {
            this.txtHostName.ReadOnly = false;
            this.txtHostPort.ReadOnly = false;
            this.txtDataBase.ReadOnly = false;
            this.txtUserName.ReadOnly = false;
            this.txtUserPwd.ReadOnly = false;
            this.btnLinkConn.Enabled = true;
        }
        private void btnLinkConn_Click(object sender, EventArgs e)
        {
            try
            {
                lsbleft.Items.Clear();//左侧列表
                lsbright.Items.Clear();//右侧列表
                listleft.Clear();
                listright.Clear();
                string hostname = this.txtHostName.Text.Trim();
                string hostport = this.txtHostPort.Text.Trim();
                string database = this.txtDataBase.Text.Trim();
                string username = this.txtUserName.Text.Trim();
                string password = this.txtUserPwd.Text.Trim();
                string connstr = "Data Source=" + hostname + ";port=" + hostport + ";User ID=" + username + ";Password=" + password + ";DataBase=" + database + ";charset=utf8";//连接字符串
                if (string.IsNullOrWhiteSpace(hostname))
                {
                    MessageBox.Show("请输入服务器!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(hostport))
                {
                    MessageBox.Show("请输入端口!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(database))
                {
                    MessageBox.Show("请输入数据库!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(username))
                {
                    MessageBox.Show("请输入用户名!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(password))
                {
                    MessageBox.Show("请输入密码!");
                    return;
                }
                setReadOnlyTrue();
                conn = new MySqlConnection(connstr);
                conn.Open();
                string sql = "show tables";
                DataTable dt = ExecuteDataTable(conn, sql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        listleft.Add(dt.Rows[i][0].ToString());
                    }
                }
                lsbleft.Items.AddRange(listleft.ToArray());//填充到左侧列表
                conn.Close();
            }
            catch (Exception ex)
            {
                setReadOnlyFalse();
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary> 
        /// 执行查询语句，返回DataTable 
        /// </summary> 
        /// <param name="SQLString">查询语句</param> 
        /// <returns>DataTable</returns> 
        public static DataTable ExecuteDataTable(MySqlConnection connection, string SQLString)
        {
            DataSet ds = new DataSet();
            try
            {
                MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                command.Fill(ds, "ds");
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                throw new Exception(ex.Message);
            }
            return ds.Tables[0];
        }
        //左边到右边
        private void btntoright_Click(object sender, EventArgs e)
        {
            foreach (string item in lsbleft.SelectedItems)
            {
                listright.Add(item);
                listleft.Remove(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }
        //左边全部到右边
        private void btnalltoright_Click(object sender, EventArgs e)
        {
            foreach (string item in lsbleft.Items)
            {
                listright.Add(item);
                listleft.Remove(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }
        //右边到左边
        private void btntoleft_Click(object sender, EventArgs e)
        {
            foreach (string item in lsbright.SelectedItems)
            {
                listright.Remove(item);
                listleft.Add(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }
        //右边全部到左边
        private void btnalltoleft_Click(object sender, EventArgs e)
        {
            foreach (string item in lsbright.Items)
            {
                listright.Remove(item);
                listleft.Add(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }
        //左边鼠标双击时
        private void lsbleft_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            foreach (string item in lsbleft.SelectedItems)
            {
                listright.Add(item);
                listleft.Remove(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }
        //右边鼠标双击时
        private void lsbright_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            foreach (string item in lsbright.SelectedItems)
            {
                listright.Remove(item);
                listleft.Add(item);
            }

            listleft.Sort();
            listright.Sort();

            lsbright.Items.Clear();
            lsbright.Items.AddRange(listright.ToArray());
            lsbleft.Items.Clear();
            lsbleft.Items.AddRange(listleft.ToArray());
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择代码存放路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                this.txtOutPut.Text = foldPath;
            }
        }
        // controller预览
        private void btnControllerPreview_Click(object sender, EventArgs e)
        {
            bool result = this.txtHostName.ReadOnly;
            if (!result)
            {
                MessageBox.Show("数据库未连接!");
                return;
            }
            if (lsbright.Items.Count == 0)
            {
                MessageBox.Show("无法预览：右边表菜单没有表存在.");
                return;
            }
            string tabName = lsbright.Items[0].ToString();
            string txtPrefix = this.txtPrefix.Text.Trim();
            string txtCommon = this.txtCommon.Text.Trim();
            string txtModularName = this.txtModularName.Text.Trim();
            if (string.IsNullOrWhiteSpace(txtPrefix))
            {
                MessageBox.Show("请输入表名前缀!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtModularName))
            {
                MessageBox.Show("请输入模块名称!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtCommon))
            {
                MessageBox.Show("请输入公共模块库名称.");
                return;
            }
            this.txtShow.Text = ControllerPreview(txtPrefix, tabName, txtModularName, txtCommon);
        }
        // model预览
        private void btnModelPreview_Click(object sender, EventArgs e)
        {
            bool result = this.txtHostName.ReadOnly;
            if (!result)
            {
                MessageBox.Show("数据库未连接!");
                return;
            }
            if (lsbright.Items.Count == 0)
            {
                MessageBox.Show("无法预览：右边表菜单没有表存在.");
                return;
            }
            string tabName = lsbright.Items[0].ToString();
            string txtPrefix = this.txtPrefix.Text.Trim();
            string txtCommon = this.txtCommon.Text.Trim();
            string txtModularName = this.txtModularName.Text.Trim();
            if (string.IsNullOrWhiteSpace(txtPrefix))
            {
                MessageBox.Show("请输入表名前缀!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtModularName))
            {
                MessageBox.Show("请输入模块名称!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtCommon))
            {
                MessageBox.Show("请输入公共模块库名称.");
                return;
            }
            this.txtShow.Text = ModelPreview(txtPrefix, tabName, txtModularName, txtCommon);
        }
        // validate预览
        private void btnValidatePreview_Click(object sender, EventArgs e)
        {
            bool result = this.txtHostName.ReadOnly;
            if (!result)
            {
                MessageBox.Show("数据库未连接!");
                return;
            }
            if (lsbright.Items.Count == 0)
            {
                MessageBox.Show("无法预览：右边表菜单没有表存在.");
                return;
            }
            string tabName = lsbright.Items[0].ToString();
            string txtPrefix = this.txtPrefix.Text.Trim();
            string txtCommon = this.txtCommon.Text.Trim();
            string txtModularName = this.txtModularName.Text.Trim();
            if (string.IsNullOrWhiteSpace(txtPrefix))
            {
                MessageBox.Show("请输入表名前缀!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtModularName))
            {
                MessageBox.Show("请输入模块名称!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtCommon))
            {
                MessageBox.Show("请输入公共模块库名称.");
                return;
            }
            this.txtShow.Text = ValidatePreview(txtPrefix, tabName, txtModularName, txtCommon);
        }
        // 生成代码
        private void btnCreateCode_Click(object sender, EventArgs e)
        {
            bool result = this.txtHostName.ReadOnly;
            if (!result)
            {
                MessageBox.Show("数据库未连接!");
                return;
            }
            if (lsbright.Items.Count == 0)
            {
                MessageBox.Show("无法预览：右边表菜单没有表存在.");
                return;
            }
            string txtPrefix = this.txtPrefix.Text.Trim();
            string txtCommon = this.txtCommon.Text.Trim();
            string txtModularName = this.txtModularName.Text.Trim();
            if (string.IsNullOrWhiteSpace(txtPrefix))
            {
                MessageBox.Show("请输入表名前缀!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtModularName))
            {
                MessageBox.Show("请输入模块名称!");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtCommon))
            {
                MessageBox.Show("请输入公共模块库名称.");
                return;
            }
            // 获取代码存放路径
            string output = this.txtOutPut.Text.Trim();
            if (!Directory.Exists(output))
            {
                Directory.CreateDirectory(output);
            }
            // 公告模型
            string output_model = "";
            output_model = output + "\\" + txtCommon + "\\model\\";
            if (!Directory.Exists(output_model))
            {
                Directory.CreateDirectory(output_model);
            }
            // 控制器
            string output_controller = "";
            output_controller = output + "\\" + txtModularName + "\\controller\\";
            if (!Directory.Exists(output_controller))
            {
                Directory.CreateDirectory(output_controller);
            }
            // 验证器
            string output_validate = "";
            output_validate = output + "\\" + txtModularName + "\\validate\\";
            if (!Directory.Exists(output_validate))
            {
                Directory.CreateDirectory(output_validate);
            }
            // 右侧表
            string className = "";
            string modelFileName = "";
            string controllerFileName = "";
            string validateFileName = "";
            string modelFileInfo = "";
            string controllerFileInfo = "";
            string validateFileInfo = "";
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);//创建UTF8无BOM文本文件
            foreach (string tabname in lsbright.Items)
            {
                className = tabname.Replace(txtPrefix, "");
                modelFileInfo = ModelPreview(txtPrefix, tabname, txtModularName, txtCommon);
                controllerFileInfo = ControllerPreview(txtPrefix, tabname, txtModularName, txtCommon);
                validateFileInfo = ValidatePreview(txtPrefix, tabname, txtModularName, txtCommon);
                modelFileName = output_model + ReplaceTableName(txtPrefix,tabname) + ".php";
                controllerFileName = output_controller + ReplaceTableName(txtPrefix, tabname) + ".php";
                validateFileName = output_validate + ReplaceTableName(txtPrefix, tabname) + ".php";
                File.WriteAllText(modelFileName, modelFileInfo, utf8WithoutBom);
                File.WriteAllText(controllerFileName, controllerFileInfo, utf8WithoutBom);
                File.WriteAllText(validateFileName, validateFileInfo, utf8WithoutBom);
            }
            MessageBox.Show("生成成功!");
        }
        // 模型预览
        private string ModelPreview(string txtPrefix, string tabName, string txtModularName, string txtCommon)
        {
            string modelNewName = ReplaceTableName(txtPrefix, tabName);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?php");
            sb.AppendLine(@"namespace app\" + txtCommon + "\\model;\r\n");
            sb.AppendLine("use think\\Model;\r\n");
            sb.AppendLine("/**");
            sb.AppendLine(" * " + author + "");
            sb.AppendLine(" * " + generate + "");
            sb.AppendLine(" * Class " + modelNewName + "");
            sb.AppendLine(" * @package app\\" + txtCommon + "\\model");
            sb.AppendLine(" */");
            sb.AppendLine("class " + modelNewName + " extends Model {\r\n");
            sb.AppendLine("}");
            return sb.ToString();
        }
        private string ValidatePreview(string txtPrefix, string tabName, string txtModularName, string txtCommon)
        {
            try
            {
                string database = this.txtDataBase.Text.Trim();
                string sql = "select * from information_schema.columns where table_schema ='" + database + "' and table_name = '" + tabName + "' ;";
                DataTable dt = ExecuteDataTable(conn, sql);
                List<string> listRule = new List<string>();
                List<string> listMessage = new List<string>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string byIntRule = "";
                        string data_type = "";
                        string column_name = "";
                        string column_comment = "";
                        string extra = "";
                        extra = dt.Rows[i]["EXTRA"].ToString();
                        data_type = dt.Rows[i]["DATA_TYPE"].ToString();
                        column_name = dt.Rows[i]["COLUMN_NAME"].ToString();
                        column_comment = dt.Rows[i]["COLUMN_COMMENT"].ToString();
                        if (extra.ToLower() != "auto_increment")
                        {
                            if (data_type == "int")
                            {
                                byIntRule = "|number";
                            }
                            listRule.Add("             '" + column_name + "'             => 'require" + byIntRule + "'");
                            listMessage.Add("        '" + column_name + ".require'             => '" + data_type + "'//" + column_comment + "");
                        }
                    }
                }
                conn.Close();
                string rule = string.Join(",\r\n", listRule.ToArray());
                string message = string.Join(",\r\n", listMessage.ToArray());
                string validateNewName = ReplaceTableName(txtPrefix, tabName);
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?php");
                sb.AppendLine(@"namespace app\" + txtModularName + "\\validate;\r\n");
                sb.AppendLine("use think\\Validate;\r\n");
                sb.AppendLine("/**");
                sb.AppendLine(" * " + author + "");
                sb.AppendLine(" * " + generate + "");
                sb.AppendLine(" * Class " + validateNewName + "");
                sb.AppendLine(" * @package app\\" + txtModularName + "\\validate");
                sb.AppendLine(" */");
                sb.AppendLine("class " + validateNewName + " extends Model {");
                sb.AppendLine("    protected $rule = [");
                sb.AppendLine(rule);
                sb.AppendLine("    ];\r\n");
                sb.AppendLine("    //以下是根据你的验证需求来写，生成工具只帮忙生成表中字段类型/字段备注说明\r\n");
                sb.AppendLine("    protected $message = [");
                sb.AppendLine(message);
                sb.AppendLine("    ];");
                sb.AppendLine("    /*");
                sb.AppendLine("    格式验证");
                sb.AppendLine("		require		验证某个字段必须");
                sb.AppendLine("		number  	或者 integer	验证某个字段的值是否为数字");
                sb.AppendLine("		float		验证某个字段的值是否为浮点数字");
                sb.AppendLine("		boolean		验证某个字段的值是否为布尔值");
                sb.AppendLine("		email		验证某个字段的值是否为email地址");
                sb.AppendLine("		array		验证某个字段的值是否为数组");
                sb.AppendLine("		accepted	验证某个字段是否为为 yes, on, 或是 1。这在确认\"服务条款\"是否同意时很有用");
                sb.AppendLine("		date		验证值是否为有效的日期");
                sb.AppendLine("		alpha		验证某个字段的值是否为字母");
                sb.AppendLine("		alphaNum	验证某个字段的值是否为字母和数字");
                sb.AppendLine("		alphaDash	验证某个字段的值是否为字母和数字，下划线_及破折号-");
                sb.AppendLine("		activeUrl	验证某个字段的值是否为有效的域名或者IP");
                sb.AppendLine("		url			验证某个字段的值是否为有效的URL地址");
                sb.AppendLine("		ip			验证某个字段的值是否为有效的IP地址,支持验证ipv4和ipv6格式的IP地址");
                sb.AppendLine("		dateFormat	验证某个字段的值是否为指定格式的日期	例如:'create_time'=>'dateFormat:y-m-d'");
                sb.AppendLine("	长度和区间验证");
                sb.AppendLine("		in			验证某个字段的值是否在某个范围 例如：'num'=>'in:1,2,3'");
                sb.AppendLine("		notIn		验证某个字段的值不在某个范围 例如：'num'=>'notIn:1,2,3'");
                sb.AppendLine("		between 	验证某个字段的值是否在某个区间 例如：'num'=>'between:1,10'");
                sb.AppendLine("		notBetween	验证某个字段的值不在某个范围 例如：'num'=>'notBetween:1,10'");
                sb.AppendLine("		length		验证某个字段的值的长度是否在某个范围 例如：'name'=>'length:4,25' 或者指定长度 'name'=>'length:4'");
                sb.AppendLine("		max			验证某个字段的值的最大长度 'name'=>'max:25'");
                sb.AppendLine("		min			验证某个字段的值的最小长度 'name'=>'min:5'");
                sb.AppendLine("		after		验证某个字段的值是否在某个日期之后 'begin_time' => 'after:2016-3-18',");
                sb.AppendLine("		before  	验证某个字段的值是否在某个日期之前 'end_time'   => 'before:2016-10-01',");
                sb.AppendLine("		expire  	验证当前操作（注意不是某个值）是否在某个有效日期之内 'expire_time'   => 'expire:2016-2-1,2016-10-01',");
                sb.AppendLine("		allowIp 	验证当前请求的IP是否在某个范围，例如：'name'   => 'allowIp:114.45.4.55',");
                sb.AppendLine("		denyIp  	验证当前请求的IP是否禁止访问，例如：'name'   => 'denyIp:114.45.4.55',");
                sb.AppendLine("	字段比较");
                sb.AppendLine("		confirm		验证某个字段是否和另外一个字段的值一致，例如：'repassword'=>'require|confirm:password'");
                sb.AppendLine("		different	验证某个字段是否和另外一个字段的值不一致，例如：'name'=>'require|different:account'");
                sb.AppendLine("		egt 或者 >=	验证是否大于等于某个值，例如：'score'=>'egt:60'	 'num'=>'>=:100'");
                sb.AppendLine("		gt 或者 >	验证是否大于某个值，例如：'score'=>'gt:60'	'num'=>'>:100'");
                sb.AppendLine("		elt 或者 <=	验证是否小于等于某个值，例如：'score'=>'elt:100'	'num'=>'<=:100'");
                sb.AppendLine("		lt 或者 <	验证是否小于某个值，例如：'score'=>'lt:100'	'num'=>'<:100'");
                sb.AppendLine("		eq 或者 = 或者 same		验证是否等于某个值，例如：'score'=>'eq:100'	'num'=>'=:100'	'num'=>'same:100'");
                sb.AppendLine("	filter验证");
                sb.AppendLine("		支持使用filter_var进行验证，例如：'ip'=>'filter:validate_ip'");
                sb.AppendLine("	正则验证");
                sb.AppendLine("		支持直接使用正则验证，例如：'zip'=>'\\d{6}', 或者 'zip'=>'regex:\\d{6}',");
                sb.AppendLine("		如果你的正则表达式中包含有|符号的话，必须使用数组方式定义。	'accepted'=>['regex'=>'/^(yes|on|1)$/i'],");
                sb.AppendLine("		上传验证");
                sb.AppendLine("		file	验证是否是一个上传文件");
                sb.AppendLine("		image:width,height,type		验证是否是一个图像文件，width height和type都是可选，width和height必须同时定义");
                sb.AppendLine("		fileExt:允许的文件后缀		验证上传文件后缀");
                sb.AppendLine("		fileMime:允许的文件类型");
                sb.AppendLine("		fileSize:允许的文件字节大小");
                sb.AppendLine("    */");
                sb.AppendLine("}");
                return sb.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
        private string ControllerPreview(string txtPrefix, string tabName, string txtModularName, string txtCommon)
        {
            try
            {
                string v = ControllerTpl();
                v = v.Replace("{#modelName#}", txtModularName);
                v = v.Replace("{#commonName#}", txtCommon);
                v = v.Replace("{#tabName#}", ReplaceTableName(txtPrefix, tabName));
                v = v.Replace("{#tabNameUp#}", tabName.Replace(txtPrefix, "").ToLower());
                return v;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
        private string ReplaceTableName(string tabPrefix, string tabName)
        {
            string r = "";
            string newTabName = tabName.Replace(tabPrefix, "");
            if (newTabName.IndexOf("_") > 0)
            {
                string[] sp = newTabName.Split('_');
                foreach (var item in sp)
                {
                    r += FunctionStr(item.ToString());
                }
            }
            else
            {
                r = FunctionStr(newTabName);
            }
            return r;
        }
        private string FunctionStr(string tabName)
        {
            string functionStr = tabName.Substring(0, 1).ToUpper() + tabName.Substring(1);
            return functionStr;
        }
        public string ControllerTpl()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<?php");
            sb.AppendLine("namespace app\\{#modelName#}\\controller;");
            sb.AppendLine("/**");
            sb.AppendLine(" * " + author + "");
            sb.AppendLine(" * " + generate + "");
            sb.AppendLine("*/");
            sb.AppendLine("use think\\Controller;");
            sb.AppendLine("use think\\View;");
            sb.AppendLine("use think\\Request;");
            sb.AppendLine("use app\\{#commonName#}\\model\\{#tabName#} as {#tabName#}Model;");
            sb.AppendLine("");
            sb.AppendLine("class {#tabName#} extends Base{");
            sb.AppendLine("    protected function _initialize() {");
            sb.AppendLine("        parent::_initialize();");
            sb.AppendLine("        $this->{#tabNameUp#}_model = new {#tabName#}Model();");
            sb.AppendLine("    }");
            sb.AppendLine("    public function index($keyword = '', $page = 1) {");
            sb.AppendLine("        $this->assign('title', '数据列表');");
            sb.AppendLine("        $pageNum = 20;");
            sb.AppendLine("        $map = [];");
            sb.AppendLine("        if ($keyword) {");
            sb.AppendLine("            $keyword = trim($keyword);");
            sb.AppendLine("            // 此处根据你自己的需求改进");
            sb.AppendLine("            $map['name'] = ['like', \"%{$keyword}%\"];");
            sb.AppendLine("        }");
            sb.AppendLine("        $list = $this->{#tabNameUp#}_model->where($map)->order(['px' => 'DESC', 'id' => 'DESC'])->paginate($pageNum, false, ['page' => $page, 'query' => ['keyword' => $keyword]]);");
            sb.AppendLine("        $this->assign('list', $list);");
            sb.AppendLine("        $this->assign('keyword', $keyword);");
            sb.AppendLine("        return $this->fetch();");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 添加页面");
            sb.AppendLine("    * @return mixed");
            sb.AppendLine("    */");
            sb.AppendLine("    public function add() {");
            sb.AppendLine("        $this->assign('title', '添加数据');");
            sb.AppendLine("        return $this->fetch();");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 保存数据");
            sb.AppendLine("    */");
            sb.AppendLine("    public function save() {");
            sb.AppendLine("        $json['code'] = 0;");
            sb.AppendLine("        if ($this->request->isPost()) {");
            sb.AppendLine("            $data = $this->request->post();");
            sb.AppendLine("            $validate_result = $this->validate($data, '{#tabName#}');//验证器");
            sb.AppendLine("            if ($validate_result !== true) {");
            sb.AppendLine("                $json['msg'] = $validate_result;");
            sb.AppendLine("            } else {");
            sb.AppendLine("                $result = $this->{#tabNameUp#}_model->allowField(true)->save($data);");
            sb.AppendLine("                if ($result !== false) {");
            sb.AppendLine("                    $json['code'] = 1;");
            sb.AppendLine("                    $json['msg'] = '保存成功';");
            sb.AppendLine("                    $json['url'] = url('index');");
            sb.AppendLine("                } else {");
            sb.AppendLine("                    $json['msg'] = '保存失败!';");
            sb.AppendLine("                }");
            sb.AppendLine("            }");
            sb.AppendLine("        } else {");
            sb.AppendLine("            $json['msg'] = '不允许非Post提交!';");
            sb.AppendLine("        }");
            sb.AppendLine("        return json($json);");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 编辑页面");
            sb.AppendLine("    * @param $id");
            sb.AppendLine("    * @return mixed");
            sb.AppendLine("    */");
            sb.AppendLine("    public function edit($id) {");
            sb.AppendLine("        $this->assign('title', '编辑数据');");
            sb.AppendLine("        $data = $this->{#tabNameUp#}_model->find($id);");
            sb.AppendLine("        $this->assign('data', $data);");
            sb.AppendLine("        return $this->fetch();");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 更新数据");
            sb.AppendLine("    * @param $id");
            sb.AppendLine("    */");
            sb.AppendLine("    public function update($id) {");
            sb.AppendLine("        $json['code'] = 0;");
            sb.AppendLine("        if ($this->request->isPost()) {");
            sb.AppendLine("            $data = $this->request->post();");
            sb.AppendLine("            $validate_result = $this->validate($data, '{#tabName#}');//验证器");
            sb.AppendLine("            if ($validate_result !== true) {");
            sb.AppendLine("                $json['msg'] = $validate_result;");
            sb.AppendLine("            } else {");
            sb.AppendLine("                $result = $this->{#tabNameUp#}_model->allowField(true)->save($data, $id);");
            sb.AppendLine("                if ($result !== false) {");
            sb.AppendLine("                    $json['code'] = 1;");
            sb.AppendLine("                    $json['msg'] = '更新成功';");
            sb.AppendLine("                    $json['url'] = $data['backurl'];");
            sb.AppendLine("                } else {");
            sb.AppendLine("                    $json['msg'] = '更新失败!';");
            sb.AppendLine("                }");
            sb.AppendLine("            }");
            sb.AppendLine("        } else {");
            sb.AppendLine("            $json['msg'] = '不允许非Post提交!';");
            sb.AppendLine("        }");
            sb.AppendLine("        return json($json);");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 删除数据");
            sb.AppendLine("    * @param int   $id");
            sb.AppendLine("    * @param array $ids");
            sb.AppendLine("    */");
            sb.AppendLine("    public function delete($id = 0, $ids = []) {");
            sb.AppendLine("        $id = $ids ? $ids : $id;");
            sb.AppendLine("        $json['code'] = 0;");
            sb.AppendLine("        if ($id) {");
            sb.AppendLine("            $result = $this->{#tabNameUp#}_model->destroy($id);");
            sb.AppendLine("            if ($result) {");
            sb.AppendLine("                $json['code'] = 1;");
            sb.AppendLine("                $json['msg'] = '删除成功';");
            sb.AppendLine("            } else {");
            sb.AppendLine("                $json['msg'] = '删除失败!';");
            sb.AppendLine("            }");
            sb.AppendLine("        } else {");
            sb.AppendLine("            $json['msg'] = '请选择需要删除的数据!';");
            sb.AppendLine("        }");
            sb.AppendLine("        return json($json);");
            sb.AppendLine("    }");
            sb.AppendLine("    /**");
            sb.AppendLine("    * 排序");
            sb.AppendLine("    * @param array  $idarr");
            sb.AppendLine("    * @param array  $px");
            sb.AppendLine("    * @param string $type 操作类型");
            sb.AppendLine("    */");
            sb.AppendLine("    public function toggle($idarr = [], $px = [])");
            sb.AppendLine("    {");
            sb.AppendLine("        $json['code'] = 0;");
            sb.AppendLine("        $data = [];");
            sb.AppendLine("        if (!empty($idarr)) {");
            sb.AppendLine("            foreach ($idarr as $k => $v) {");
            sb.AppendLine("                $data[] = ['id' => $v, 'px' => $px[$k]];");
            sb.AppendLine("            }");
            sb.AppendLine("            $result = $this->{#tabNameUp#}_model->saveAll($data);");
            sb.AppendLine("            if ($result) {");
            sb.AppendLine("                $json['code'] = 1;");
            sb.AppendLine("                $json['msg'] = '排序成功';");
            sb.AppendLine("            } else {");
            sb.AppendLine("                $json['msg'] = '排序失败';");
            sb.AppendLine("            }");
            sb.AppendLine("        } else {");
            sb.AppendLine("            $json['msg'] = '请选择需要排序的数据';");
            sb.AppendLine("        }");
            sb.AppendLine("        return json($json);");
            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            ConfigHelper.UpdateAppConfig("hostname", this.txtHostName.Text.Trim());
            ConfigHelper.UpdateAppConfig("hostport", this.txtHostPort.Text.Trim());
            ConfigHelper.UpdateAppConfig("database", this.txtDataBase.Text.Trim());
            ConfigHelper.UpdateAppConfig("username", this.txtUserName.Text.Trim());
            ConfigHelper.UpdateAppConfig("password", this.txtUserPwd.Text.Trim());
            ConfigHelper.UpdateAppConfig("prefix", this.txtPrefix.Text.Trim());
            ConfigHelper.UpdateAppConfig("ModularName", this.txtModularName.Text.Trim());
            ConfigHelper.UpdateAppConfig("Common", this.txtCommon.Text.Trim());
            ConfigHelper.UpdateAppConfig("OutPut", this.txtOutPut.Text.Trim());
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            setReadOnlyFalse();
        }
    }
}